﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication.Models;

namespace MvcApplication.Controllers
{
    public class HopDongController : Controller
    {
        Winapp111020DataContext dataContext;
        public HopDongController()
        {
            dataContext = new Winapp111020DataContext();
        }

        /// <summary>
        /// Display dropdownlist of phongbans
        /// </summary>
        /// <param name="selectedPhongBan">Id phongban will be selected</param>
        private void PopulatePhongBanDropDownList(int selectedPhongBan = 0)
        {
            var pb = from p in dataContext.PhongBanModels
                                    where p.deleted == false
                     //orderby p.ten_phong_ban
                                   select p;
            ViewBag.phong_ban = new SelectList(pb, "id_phong_ban", "ten_phong_ban",
                pb.Count(p => p.id_phong_ban == selectedPhongBan) == 0 ? pb.First().id_phong_ban : selectedPhongBan);
        }

        /// <summary>
        /// Display dropdownlist of nhansus
        /// </summary>
        /// <param name="selectedPhongBan">Id phongban to filter</param>
        /// <param name="selectedNhanSu">Id nhansu will be selected</param>
        private void PopulateNhanSuDropDownList(int selectedPhongBan = 0, int selectedNhanSu = 0)
        {
            var ns = from n in dataContext.NhanSuModels
                     where n.id_phong_ban == (dataContext.PhongBanModels.Count(p=>p.id_phong_ban==selectedPhongBan && p.deleted == false)==0?dataContext.PhongBanModels.First(p=>p.deleted == false).id_phong_ban:selectedPhongBan) 
                            && n.deleted == false
                     orderby n.ho_ten
                     select n;
            ViewBag.nhan_su = new SelectList(ns, "id_nhan_su", "ho_ten", selectedNhanSu > 0 ? selectedNhanSu : ns.First().id_nhan_su);
        }

        /// <summary>
        /// Display list of hopdongs
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(object selectedPhongBan = null, object selectedNhanSu = null)
        {
            int id_pb = 0, id_ns = 0;
            int.TryParse(selectedPhongBan.ToString(), out id_pb);
            int.TryParse(selectedNhanSu.ToString(), out id_ns);
            if (id_pb!=0 && dataContext.PhongBanModels.Count(p => p.id_phong_ban == id_pb && p.deleted == false) == 0)
            {
                return HttpNotFound("Không tìm thấy phòng ban");
            }
            if (id_ns != 0 && (dataContext.NhanSuModels.Count(n => n.id_nhan_su == id_ns && n.deleted == false) == 0 ||
                dataContext.NhanSuModels.Single(n => n.id_nhan_su == id_ns).id_phong_ban != id_pb))
            {
                return HttpNotFound("Không tìm thấy nhân sự");
            }
                        
            PopulatePhongBanDropDownList(id_pb);
            PopulateNhanSuDropDownList(id_pb, id_ns);

            ViewBag.selectedPhongBan = selectedPhongBan;
            ViewBag.selectedNhanSu = selectedNhanSu;
            var hopdongs = from h in dataContext.HopDongModels
                           where h.deleted == false 
                                && h.id_nhan_su == (dataContext.NhanSuModels.Count(n=>n.id_nhan_su==id_ns && n.deleted == false)==0?dataContext.NhanSuModels.First(n=>n.deleted==false).id_nhan_su:id_ns)
                           select h;

            //ViewBag.validNhanSu = dataContext.NhanSuModels.Count(n => n.id_nhan_su == selectedNhanSu);
            return View(hopdongs);
        }

        /// <summary>
        /// Display page to create hopdong
        /// </summary>
        /// <returns></returns>  
        [HttpPost]
        public ActionResult Create(int selectedPhongBan, int selectedNhanSu)
        {
            if (dataContext.NhanSuModels.Count(n => n.id_nhan_su == selectedNhanSu && n.deleted == false) > 0)
            {
                PopulatePhongBanDropDownList(selectedPhongBan);
                PopulateNhanSuDropDownList(selectedPhongBan, selectedNhanSu);

                ViewBag.selectedPhongBan = selectedPhongBan;
                ViewBag.selectedNhanSu = selectedNhanSu;

                return View();
            }
            else
            {
                return HttpNotFound();
            }
        }
        [HttpPost]
        public ActionResult CreateSubmit(HopDongModel hd)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    dataContext.HopDongModels.InsertOnSubmit(hd);
                    dataContext.SubmitChanges();
                    return RedirectToAction("Index", new
                    {
                        selectedPhongBan = hd.NhanSuModel.id_phong_ban,
                        selectedNhanSu = hd.id_nhan_su
                    });
                }
            }
            catch (Exception exc)
            {
                ModelState.AddModelError("", exc);
            }
            return View(hd);
        }

        /// <summary>
        /// Display details of hopdong
        /// </summary>
        /// <param name="id">id of hopdong</param>
        /// <returns></returns>
        public ActionResult Details(int id = 0)
        {
            var hopdong = dataContext.HopDongModels.SingleOrDefault(hd => hd.id_hop_dong == id && hd.deleted == false);
            if (hopdong == null)
            {
                return HttpNotFound("Không tìm thấy hợp đồng");
            }
            else
            {
                return View(hopdong);
            }
        }


        /// <summary>
        /// Display details of hopdong to be edit
        /// </summary>
        /// <param name="id">id of hopdong</param>
        /// <returns></returns>
        public ActionResult Edit(int id = 0)
        {
            var hopdong = dataContext.HopDongModels.SingleOrDefault(hd => hd.id_hop_dong == id && hd.deleted == false);
            if (hopdong == null)
            {
                return HttpNotFound("Không tìm thấy hợp đồng");
            }
            else
            {
                return View(hopdong);
            }
        }
        [HttpPost]
        public ActionResult Edit(HopDongModel hd)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    dataContext.HopDongModels.DeleteOnSubmit(dataContext.HopDongModels.Single(h => h.id_hop_dong == hd.id_hop_dong));
                    dataContext.HopDongModels.InsertOnSubmit(hd);
                    dataContext.SubmitChanges();
                    return RedirectToAction("Index", new
                    {
                        selectedPhongBan = hd.NhanSuModel.id_phong_ban,
                        selectedNhanSu = hd.id_nhan_su
                    });
                }
            }
            catch (Exception exc)
            {
                ModelState.AddModelError("", exc);                    
            }
            return View(hd);
        }
        
        /// <summary>
        /// Display details of hopdong before deleting
        /// </summary>
        /// <param name="id">id of hopdong</param>
        /// <returns></returns>
        public ActionResult Delete(string submitChangesError = "",int id = 0)
        {
            var hopdong = dataContext.HopDongModels.SingleOrDefault(hd => hd.id_hop_dong == id && hd.deleted == false);
            if (hopdong == null)
            {
                return HttpNotFound("Không tìm thấy Hợp đồng");
            }
            else
            {
                if (submitChangesError !=string.Empty)
                {
                    ViewBag.ErrorMessage = "Không thể xóa hợp đồng: " + submitChangesError;
                }
                return View(hopdong);
            }
        }
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                HopDongModel hd = dataContext.HopDongModels.SingleOrDefault(h => h.id_hop_dong == id);
                hd.deleted = true;
                //dataContext.HopDongModels.DeleteOnSubmit(hd);
                dataContext.SubmitChanges();
                return RedirectToAction("Index", new
                {
                    selectedPhongBan = hd.NhanSuModel.id_phong_ban,
                    selectedNhanSu = hd.id_nhan_su
                });
            }
            catch (Exception exc)
            {
                //Log the error (add a variable name after DataException)
                return RedirectToAction("Delete",
                    new System.Web.Routing.RouteValueDictionary {
                { "submitChangesError", exc.Message },
                { "id", id } });
            }
        }

    }
}
